//
//  DualMediationMAXNativeADManager.m
//  DualMediationSDK
//
//  Created by Assistant on 2024/01/01.
//  Copyright © 2024 DualMediation. All rights reserved.
//

#import "DualMediationMAXNativeADManager.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import "DMConfigReader.h"
#import "DMThinkingManager.h"

#if __has_include(<AppLovinSDK/AppLovinSDK.h>)
#import <AppLovinSDK/AppLovinSDK.h>
#define APPLOVIN_SDK_AVAILABLE 1
#else
#define APPLOVIN_SDK_AVAILABLE 0
#endif


// 位置枚举已移至DMNativeTypes.h统一定义

@interface DualMediationMAXNativeADManager ()
#if APPLOVIN_SDK_AVAILABLE
<MANativeAdDelegate>
@property (nonatomic, strong) MANativeAdLoader *nativeAdLoader;
@property (nonatomic, strong) MAAd *nativeAd;
@property (nonatomic, strong) MANativeAdView *nativeAdView;
#endif
#if UIKIT_AVAILABLE
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, weak) UIViewController *currentVC;
#endif
@property (nonatomic, assign) BOOL hasShowAd;
@property (nonatomic, assign, readwrite) BOOL isUserClosed;
@property (nonatomic, strong) NSString *currentScene;
@end

@implementation DualMediationMAXNativeADManager

static DualMediationMAXNativeADManager *_nativeAd = nil;

+ (instancetype)sharedNativeADManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _nativeAd = [[self alloc] init];
        [IMLogUtils info:IMLogTagSDKInit format:@"📰 [MAX Native] 单例管理器创建成功"];
    });
    return _nativeAd;
}

#if UIKIT_AVAILABLE
- (UIViewController *)topMostViewController {
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }
    return topController;
}
#endif

#pragma mark - Public

- (void)setCurrentScene:(NSString *)scene {
    self.currentScene = scene;
}

- (void)initWithNativead {
    [self loadNativeAd];
    [IMLogUtils info:IMLogTagAd format:@"📰 [MAX Native] 初始化 MAX 原生广告"];
}

- (void)loadNativeAd
{
    if (self.isUserClosed) {
        [IMLogUtils info:IMLogTagAd format:@"📰 [MAX Native] ❌ 用户已主动关闭广告，拒绝加载"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📰 [MAX Native] ========== 开始加载原生广告 =========="];
    
#if APPLOVIN_SDK_AVAILABLE
    // 1. 销毁旧广告
    if (self.nativeAd) {
        [self destroyNativeAd];
    }
    
    // 2. 创建并加载新广告
    // 先安全获取配置中的 MAX 原生广告位
    [[DMConfigReader sharedInstance] loadConfig];
    NSArray<DMAdUnitConfig *> *nativeConfigs = [[DMConfigReader sharedInstance] nativeAdConfigs];
    NSString *adUnitId = nil;
    for (DMAdUnitConfig *cfg in nativeConfigs) {
        if ([cfg.ad_type isEqualToString:@"MAX"] && cfg.ad_unitID.length > 0) {
            adUnitId = cfg.ad_unitID;
            break;
        }
    }
    
    if (adUnitId.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"📰 [MAX Native] ❌ 配置中未找到 MAX 原生广告位，跳过加载"];
        // 通知上层失败，避免沉默
        NSError *cfgError = [NSError errorWithDomain:@"MAXNativeAdError"
                                               code:400
                                           userInfo:@{ NSLocalizedDescriptionKey: @"No MAX Native ad unit configured" }];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToLoadNativeForScene:error:)]) {
            [self.delegate dmAdManager:nil didFailToLoadNativeForScene:self.currentScene ?: @"DEFAULT_NATIVE_SCENE" error:cfgError];
        }
        self.isLoadNativeAd = NO;
        return;
    }
    
    self.nativeAdLoader = [[MANativeAdLoader alloc] initWithAdUnitIdentifier:adUnitId];
    self.nativeAdLoader.nativeAdDelegate = self;
    
    [IMLogUtils info:IMLogTagAd format:@"📰 [MAX Native] 开始加载原生广告: %@", adUnitId];
    [self.nativeAdLoader loadAd];
#else
    [IMLogUtils warning:IMLogTagAd format:@"📰 [MAX Native] ❌ AppLovin SDK 不可用，无法加载原生广告"];
#endif
}

// 外部显示接口已移除，统一通过DualMediationSDKPublic调用

- (void)renderAdToContainer:(UIView *)containerView {
    if (!containerView) {
        [IMLogUtils warning:IMLogTagAd format:@"📰 [MAX Native] ❌ 容器视图为空，无法渲染广告"];
        return;
    }
    
    self.containerView = containerView;
    
    // 如果广告已加载，立即渲染
    if (self.nativeAd) {
        [self renderNativeAd];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📰 [MAX Native] 广告尚未加载，等待加载完成后渲染"];
    }
}

- (void)renderNativeAd
{
#if UIKIT_AVAILABLE && APPLOVIN_SDK_AVAILABLE
    if (!self.nativeAd || !self.containerView) {
        [IMLogUtils warning:IMLogTagAd format:@"📰 [MAX Native] ❌ 无法渲染：广告或容器为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📰 [MAX Native] 开始渲染原生广告"];
    
    // 创建原生广告视图
    UINib *nativeAdViewNib = [UINib nibWithNibName:@"MANativeAdView" bundle:[NSBundle bundleForClass:[MANativeAdView class]]];
    self.nativeAdView = [nativeAdViewNib instantiateWithOwner:nil options:nil].firstObject;
    
    // 绑定原生广告数据
    [self.nativeAdLoader renderNativeAdView:self.nativeAdView withAd:self.nativeAd];
    
    // 添加到容器
    self.nativeAdView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:self.nativeAdView];
    
    // 设置约束
    [NSLayoutConstraint activateConstraints:@[
        [self.nativeAdView.topAnchor constraintEqualToAnchor:self.containerView.topAnchor],
        [self.nativeAdView.leadingAnchor constraintEqualToAnchor:self.containerView.leadingAnchor],
        [self.nativeAdView.trailingAnchor constraintEqualToAnchor:self.containerView.trailingAnchor],
        [self.nativeAdView.bottomAnchor constraintEqualToAnchor:self.containerView.bottomAnchor]
    ]];
    
    [IMLogUtils info:IMLogTagAd format:@"📰 [MAX Native] ✅ 原生广告渲染完成"];
    // 新增 AD_Native_show 埋点
    @try {
        double ecpm = self.nativeAd.revenue * 1000.0;
        NSDictionary *nativeShowParams = @{
            @"w_scene": self.currentScene ?: @"DEFAULT_NATIVE_SCENE",
            @"w_revenue": @(ecpm)
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"AD_Native_show" jsonStr:nativeShowParams];
        [IMLogUtils info:IMLogTagAd format:@"📰 [MAX Native] 事件上报: AD_Native_show, w_revenue: %.2f", ecpm];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"📰 [MAX Native] 事件上报异常: %@", exception.reason];
    }
    
    // 通知DMAdDelegate展示成功
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didShowNativeForScene:adId:)]) {
        [self.delegate dmAdManager:nil didShowNativeForScene:self.currentScene ?: @"DEFAULT_NATIVE_SCENE" adId:self.nativeAd.adUnitIdentifier ?: @"unknown"];
    }
#else
    [IMLogUtils warning:IMLogTagAd format:@"📰 [MAX Native] ❌ UIKit或AppLovin SDK不可用，无法渲染原生广告"];
#endif
}

// 外部显示接口已移除，统一通过DualMediationSDKPublic调用

- (void)destroyNativeAd
{
    [IMLogUtils info:IMLogTagAd format:@"📰 [MAX Native] 💥 销毁原生广告"];
    
#if UIKIT_AVAILABLE
    if (self.containerView) {
        [self.containerView removeFromSuperview];
        self.containerView = nil;
    }
#endif
    
#if APPLOVIN_SDK_AVAILABLE
    if (self.nativeAdView) {
        [self.nativeAdView removeFromSuperview];
        self.nativeAdView = nil;
    }
    
    self.nativeAd = nil;
    self.nativeAdLoader = nil;
#endif
    
    self.isLoadNativeAd = NO;
}

#pragma mark - MANativeAdDelegate

#if APPLOVIN_SDK_AVAILABLE
- (void)didLoadNativeAd:(MANativeAdView *)nativeAdView forAd:(MAAd *)ad {
    [IMLogUtils info:IMLogTagNative format:@"📰 [MAX Native] 原生广告加载成功"];
    
    self.nativeAd = ad;
    self.nativeAdView = nativeAdView;
    self.isLoadNativeAd = YES;
    
    // 通知DMAdDelegate加载成功
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didLoadNativeForScene:adId:)]) {
        [self.delegate dmAdManager:nil didLoadNativeForScene:self.currentScene ?: @"DEFAULT_NATIVE_SCENE" adId:ad.adUnitIdentifier ?: @"unknown"];
    }
    
    // 如果有待展示的请求，立即渲染
    if (self.containerView && !self.isUserClosed) {
        [IMLogUtils info:IMLogTagNative format:@"📰 [MAX Native] 检测到待展示请求，立即渲染广告"];
        [self renderNativeAd];
    }
}

- (void)didFailToLoadNativeAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error {
    [IMLogUtils error:IMLogTagNative format:@"📰 [MAX Native] 原生广告加载失败: %@, 错误码: %ld", 
                     error.message, (long)error.code];
    
    self.isLoadNativeAd = NO;
    
    // 通知DMAdDelegate加载失败
    NSError *nsError = [NSError errorWithDomain:@"MAXNativeAdError" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.message ?: @"Unknown error"}];
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToLoadNativeForScene:error:)]) {
        [self.delegate dmAdManager:nil didFailToLoadNativeForScene:self.currentScene ?: @"DEFAULT_NATIVE_SCENE" error:nsError];
    }
    
    // 延迟重新加载
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!self.isUserClosed) {
            [IMLogUtils info:IMLogTagNative format:@"📰 [MAX Native] 5秒后重新加载原生广告"];
            [self loadNativeAd];
        }
    });
}

- (void)didClickNativeAd:(MAAd *)ad {
    [IMLogUtils info:IMLogTagNative format:@"📰 [MAX Native] 原生广告被点击"];
    
    // 通知DMAdDelegate点击事件
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didClickNativeForScene:adId:)]) {
        [self.delegate dmAdManager:nil didClickNativeForScene:self.currentScene ?: @"DEFAULT_NATIVE_SCENE" adId:ad.adUnitIdentifier ?: @"unknown"];
    }
}
#endif



@end
